package org.zcl.govern.server;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zcl.govern.common.utils.StringUtils;
import org.zcl.govern.server.config.Configuration;
import org.zcl.govern.server.config.ConfigurationException;
import org.zcl.govern.server.constant.NodeType;
import org.zcl.govern.server.node.NodeStatus;
import org.zcl.govern.server.node.master.MasterNode;

/**
 * 代表的是服务治理平台的server
 * @author zhaocongliang
 */
public class GovernServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(GovernServer.class);
    private static final long SHUTDOWN_CHECK_INTERVAL = 300L;

    /**
     * 服务治理平台server端的启动入口
     * @param args
     */
    public static void main(String[] args) {
        try {
            LOGGER.info("starting govern server......");

            // 初始化节点状态
            NodeStatus nodeStatus = NodeStatus.getInstance();
            nodeStatus.setStatus(NodeStatus.INITIALIZING);

            // 进行配置文件的解析
            String configPath = args[0];
            if(StringUtils.isEmpty(configPath)) {
                throw new ConfigurationException("configuration file path cannot be empty......");
            }
            Configuration configuration = Configuration.getInstance();
            configuration.parse(configPath);

            // 启动当前这个节点
            String nodeType = configuration.getNodeType();
            startNode(nodeType);

            // 完成节点的启动，设置节点状态为：运行中
            nodeStatus.setStatus(NodeStatus.RUNNING);

            LOGGER.info("node started, it is running now......");

            // 让系统无限循环等待系统停止
            waitForShutdown();
        } catch(ConfigurationException e) {
            LOGGER.error("encounter error when parsing configuration file", e);
            System.exit(2);
        } catch (InterruptedException e) {
            LOGGER.error("encounter thread interrupted error", e);
            System.exit(1);
        }
    }

    /**
     * 等待节点被停止
     */
    private static void waitForShutdown() throws InterruptedException {
        while(NodeStatus.RUNNING == NodeStatus.get()) {
            Thread.sleep(SHUTDOWN_CHECK_INTERVAL);
        }
    }

    /**
     * 启动当前这个节点
     * @param nodeType 节点类型
     */
    private static void startNode(String nodeType) {
        if(NodeType.MASTER.equals(nodeType)) {
            MasterNode masterNode = new MasterNode();
            masterNode.start();
        }
    }
}
